package com.zero.guava.samples.baseDemo;

import com.google.common.base.Splitter;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;

/**
 * 使用guava提供的splitter
 */
public class SplitterDemo {

    private static String separator = "|";// 分隔符
    private static String separator2 = "=";// 分隔符（mapSplitter）

    private static String string = "i hate u=u hate me |i like u=u like me |||i love u=u love me";// 测试用字符串

    private static String teststring2 = "0102030405060708091011121314";// 测试用字符串

    private static String teststring3 = "0102add4max6070kanpiaoxue314";// 测试用字符串


    public static void main(String[] args) {

        testSplitter();
        testMapSplitter();
        testLimitSplitter();
        testPatternSplitter();
        testPatternSplitter2();
    }

    public static void testSplitter(){

        //omitEmptyStrings方法用于忽略分割后产生的空值
        List<String> strings = Splitter.on(separator).omitEmptyStrings().splitToList(string);
        System.out.println(strings);

        // trimResults方法用于处理分割后每一项中的空白符
        Iterable<String> strings1 = Splitter.on(separator).trimResults().split(string);
        System.out.println(strings1);
    }

    public static void testMapSplitter() {

        Map<String, String> stringMap = Splitter.on(separator).omitEmptyStrings().withKeyValueSeparator(separator2).split(string);
        Set<String> stringSet = stringMap.keySet();
        System.out.println(stringMap);
        System.out.println(stringSet);
    }

    //使用limit(3)方法来限制分割的元素为3个
    public static void testLimitSplitter(){
        List<String> stringList = Splitter.fixedLength(2).limit(3).splitToList(teststring2);
        System.out.println(stringList);
    }

    //onPattern,使用正则匹配
    public static void testPatternSplitter(){
        List<String> strings = Splitter.onPattern("[a-z]").omitEmptyStrings().splitToList(teststring3);
        System.out.println(strings);
    }


    //使用on(Pattern separatorPattern)的方法，用知道的正则表达式[a-z]来生成list
    public static void testPatternSplitter2(){
        Pattern pattern = Pattern.compile("[a-z]");
        List<String> strings = Splitter.on(pattern).omitEmptyStrings().splitToList(teststring3);
        System.out.println(strings);
    }
}
